package com.example.forum.services.impl;
import com.example.forum.commen.AppResult;
import com.example.forum.commen.ResultCode;
import com.example.forum.dao.UserMapper;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Board;
import com.example.forum.model.User;
import com.example.forum.services.IUserService;
import com.example.forum.utils.MD5Util;
import com.example.forum.utils.StringUtil;
import com.example.forum.utils.UUIDUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.Date;

@Slf4j
@Service
public class UserServiceImpl implements IUserService {
    @Resource
    private UserMapper userMapper;
    @Override
    public void createNormalUser(User user) {
        //1.非空校验
        if(user == null || StringUtil.isEmpty(user.getUsername())
        || StringUtil.isEmpty(user.getNickname()) || StringUtil.isEmpty(user.getPassword())
        || StringUtil.isEmpty(user.getSalt())) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常,统一抛出ApplicationException
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2.查询用户信息
        User exitUser = userMapper.selectByUserName(user.getUsername());
        //判断用户是否存在
        if(exitUser != null) {
            //打印日志
            log.info(ResultCode.FAILED_USER_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }
        //3.新镇用户
        user.setGender((byte)2);
        user.setArticleCount(0);
        user.setIsAdmin((byte)0);
        user.setState((byte)0);
        user.setDeleteState((byte)0);
        //当前日期
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);
        //写入数据库
        int ret = userMapper.insertSelective(user);
        if(ret != 1) {
            //打印日志
            log.info(ResultCode.FAILED_CREATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //打印日志
        log.info("新增用户成功。username = "+user.getUsername()+" ");
    }

    @Override
    public User selectByUserName(String username) {
        //非空校验
        if(StringUtil.isEmpty(username)) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //返回查询结果
        return userMapper.selectByUserName(username);
    }

    @Override
    public User login(String username, String password) {
        //1.非空校验
        if(StringUtil.isEmpty(username) || StringUtil.isEmpty(password)) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString()+" , username =  "+username);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2.接收用户名查询用户信息
        User user = selectByUserName(username);
        //3.对结果做非空校验
        if(user == null) {
            //打印日志
            log.warn(ResultCode.FAILED_LOGIN.toString()+" , username : "+username);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //4.对面密码做校验
        String  encryptPassword = MD5Util.md5Salt(password,user.getSalt());
        //5.用密文和数据库存的用户密码作比较
        if(!encryptPassword.equals(user.getPassword())) {
            //打印日志
            log.warn(ResultCode.FAILED_LOGIN.toString()+",密码错误,username = "+ username);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //打印登录成功的日志
        log.info("登录成功,username = "+username);
        //登录成功，返回用户信息
        return user;
    }

    @Override
    public User selectById(Long id) {
        //非空校验
        if(id == null) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用DAO层查询数据并获取对象
        User user = userMapper.selectByPrimaryKey(id);
        //返回结果
        return user;
    }

    @Override
    public void addOneArticleCountById(Long id) {
        if(id == null || id<= 0) {
            //打印日志
            log.warn(ResultCode.FAILED_USER_ARTICLE_COUNT.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_ARTICLE_COUNT));
        }
        //查询用户信息
        User user = userMapper.selectByPrimaryKey(id);
        if(user == null) {
            //打印日志
            log.warn(ResultCode.ERROR_IS_NULL.toString()+",user id ="+id);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //更新用户的发帖数量
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount()+1);
        //更新数据库
       int row = userMapper.updateByPrimaryKeySelective(updateUser);
       if(row != 1) {
           log.warn(ResultCode.FAILED.toString()+"受影响的行数不等于1");
           throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
       }
    }

    @Override
    public void subOneArticleCountById(Long id) {
        if(id == null || id<= 0) {
            //打印日志
            log.warn(ResultCode.FAILED_USER_ARTICLE_COUNT.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_ARTICLE_COUNT));
        }
        //查询用户信息
        User user = userMapper.selectByPrimaryKey(id);
        if(user == null) {
            //打印日志
            log.warn(ResultCode.ERROR_IS_NULL.toString()+",user id ="+id);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //更新用户的发帖数量
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount()-1);
        if(updateUser.getArticleCount() < 0) {
            updateUser.setArticleCount(0);
        }
        //更新数据库
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row != 1) {
            log.warn(ResultCode.FAILED.toString()+"受影响的行数不等于1");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyInfo(User user) {
        //非空校验
        if(user == null || user.getId() == null || user.getId() <= 0) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //校验用户是否存在
        User existUser = userMapper.selectByPrimaryKey(user.getId());
        if(existUser == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        //定义标志位,校验参数
        boolean checkAttr = false; //表示检验失败
        //定义用于更新的对象,防止传入USer对象设置了其他属性
        User updateUser = new User();
        //设置用户id
        updateUser.setId(user.getId());
        //对每个参数进行校验
        if(!StringUtil.isEmpty(user.getUsername())
           && !existUser.getUsername().equals(user.getUsername())) {
            //需要更新用户名时进行唯一性校验
            User checkUser = userMapper.selectByUserName(user.getUsername());
            if(checkUser != null) {
                log.warn(ResultCode.FAILED_USER_EXISTS.toString());
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS.toString()));
            }
            //数据库中没有找到相应用户,表示可以修改
            updateUser.setUsername(user.getUsername());
            //更新标志位
            checkAttr = true;
        }
        //校验昵称
        if(!StringUtil.isEmpty(user.getNickname())
            && !existUser.getNickname().equals(user.getNickname())) {
            //设置昵称
            updateUser.setNickname(user.getNickname());
            checkAttr = true;
        }
        //校验性别
        if(user.getGender() != null && existUser.getGender() != user.getGender()) {
            updateUser.setGender(user.getGender());
            //合法性校验
            if(updateUser.getGender() > 2 || updateUser.getGender() < 0) {
                updateUser.setGender((byte) 2);
            }
            checkAttr = true;
        }
        //校验邮箱
        if(!StringUtil.isEmpty(user.getEmail())
                && !user.getEmail().equals(existUser.getEmail())) {
            //设置邮箱
            updateUser.setEmail(user.getEmail());
            checkAttr = true;
        }
        //校验电话号码
        if(!StringUtil.isEmpty(user.getPhoneNum())
                && !user.getPhoneNum().equals(existUser.getPhoneNum())) {
            //设置昵称
            updateUser.setPhoneNum(user.getPhoneNum());
            checkAttr = true;
        }
        //校验个人简介
        if(!StringUtil.isEmpty(user.getRemark())
                && !user.getRemark().equals(existUser.getRemark())) {
            //设置昵称
            updateUser.setRemark(user.getRemark());
            checkAttr = true;
        }
        //根据标志位决定是否可以更新
        if(checkAttr == false) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用Dao
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row != 1) {
            log.warn(ResultCode.FAILED.toString()+"受影响的行数不等于1");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyPassword(Long id, String newpassword, String oldPassword) {
        //非空校验
        if(id == null || id <= 0 || StringUtil.isEmpty(newpassword) || StringUtil.isEmpty(oldPassword)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //查询用户是否存在,获取用户信息
        User user = userMapper.selectByPrimaryKey(id);
        if(user == null || user.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //校验老密码是否正确
        //对老密码进行加密，获取密文
        String oldEncryPassword = MD5Util.md5Salt(oldPassword,user.getSalt());
        //与当前用户密码进行比较
        if(!oldEncryPassword.equals(user.getPassword())) {
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        // 生成新的盐值
        String salt = UUIDUtil.UUID_32();
        //生成新的密文
        String encryPassword = MD5Util.md5Salt(newpassword,salt);
        //构造更新对象
        User updateUser = new User();
        updateUser.setId(user.getId());//用户Id
        updateUser.setSalt(salt);//新盐
        updateUser.setPassword(encryPassword);//新密码对应的密文
        updateUser.setUpdateTime(new Date());//更新时间
        //调用DAO
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString()+"受影响的行数不等于1");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }
}
